<?php

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/3/6
 * Time: 15:56
 */
namespace Admin\Model;
use Think\Model;
use Think\Upload;

class GoodsModel extends Model
{
    /*****/
    protected $insertField = 'goods_name,market_price,shop_price,goods_desc,is_on_sale,goods_desc,logo,mbig_logo,big_logo,mid_logo,sm_logo,brand_id,cat_id,addtime,promote_price,promote_start_date,promote_end_date,is_new,is_hot,is_best,sort_num,is_floor';

    protected $updateField = array('id,goods_name,market_price,shop_price,is_on_sale,goods_desc,brand_id,cat_id,type_id,promote_price,promote_start_date,promote_end_date,is_new,is_hot,is_best,sort_num,is_floor');

    protected $_auto = array(
        array('addtime','getDate',1,'callback')
    );

    protected $_validate = array(
        array('cat_id' , 'require' , '必须选择主分类!' , 1),
        array('goods_name','require','商品名称不能为空!',1),
        array('market_price','currency','市场价格必须是货币类型!',1),
        array('shop_price','currency','本店价格必须是货币类型!',1),
        //array('addtime','getDate','callback')
    );

    public function getDate()
    {
        return date("Y-m-d H:i:s",NOW_TIME);
    }

    //过滤文本域的XSS攻击
    public function _before_insert(&$data,$option)
    {
        if(!$data['promote_start_date'])
            unset($data['promote_start_date']);
        if(!$data['promote_end_date'])
            unset($data['promote_end_date']);

        //$data['addtime'] = $this->getDate();
        $data['goods_desc'] = removeXSS($_POST['goods_desc']);

        /*******************处理logo*********************/
        if ($_FILES['logo']['error']==0){
            $upload = new \Think\Upload();
            $upload->maxSize = 1024 * 1024;
            $upload->exts = array('jpg','jpeg','png','gif');
            $upload->rootPath = './Public/Uploads/';
            $upload->savePath = 'Goods/';
            $info = $upload->upload();//接收参数
            if (!$info) {
                $this->error = $upload->getError();
                return false;
            } else {
              /*****************缩略图*******************/
              $logo     = $info['logo']['savepath'].$info['logo']['savename'];
              $mbiglogo = $info['logo']['savepath'].'mbig_'.$info['logo']['savename'];
              $biglogo  = $info['logo']['savepath'].'big_'.$info['logo']['savename'];
              $midlogo  = $info['logo']['savepath'].'mid_'.$info['logo']['savename'];
              $smlogo   = $info['logo']['savepath'].'sm_'.$info['logo']['savename'];

                $image = new \Think\Image();
                $image->open('./Public/uploads/'.$logo);
                $image->thumb(700,700)->save('./Public/uploads/'.$mbiglogo);
                $image->thumb(350,350)->save('./Public/uploads/'.$biglogo);
                $image->thumb(130,130)->save('./Public/uploads/'.$midlogo);
                $image->thumb(50,50)->save('./Public/uploads/'.$smlogo);

                $data['logo']     = $logo;
                $data['mbig_logo'] = $mbiglogo;
                $data['big_logo']  = $biglogo;
                $data['mid_logo']  = $midlogo;
                $data['sm_logo']   = $smlogo;
            }

        }

    }

    public function _before_update(&$data,$option){
        $id = $option['where']['id'];
        /************修改商品属性**************/
        $gaid = I('post.goods_attr_id');
        $attrValue = I('post.attr_value');
        $gaModel = D('goods_attr');
        $_i = 0;
        foreach ($attrValue as $k => $v) {
            foreach($v as $k1 =>$v1){
                if($gaid[$_i]){
                    $gaModel->add(array(
                        'goods_id' => $id,
                        'attr_id'  => $k,
                        'attr_value' => $v1,
                    ));
                } else {
                     $gaModel->where(array(
                         'id' => array('eq',$gaid[$_i]),
                     ))->setField('attr_value',$_i);
                }
                $_i++;
            }
        }
        /*******分类处理********/
        $ecid = I('post.ext_cat_id');
        $gcModel = D('goods_cat');
        $gcModel ->where(array(
            'goods_id' => array('eq',$id),
        ))->delete();
        if($ecid){
            foreach ($ecid as $k => $v){
                if (empty($v))
                    continue;
                $gcModel->add(array(
                    'cat_id' => $v,
                    'goods_id' => $id,
                ));
            }
        }
        /************LOGO***********/
        if ($_FILES['logo']['error'] == 0){
            $upload = new \Think\Upload();
            $upload->maxSize = 1024 * 1024;
            $upload->exts = array('jpg','jpeg','png','gif');
            $upload->rootPath = './Public/Uploads/';
            $upload->savePath = 'Goods/';
            $info = $upload->upload();//上传文件
            if (!$info) {
                $this->error = $upload->getError();
                return false;
            } else {
                //先拼出缩略图的路径和名称
                $logo = $info['logo']['savepath'] . $info['logo']['savename'];
                $mbiglogo = $info['logo']['savepath'].'mbig_'.$info['logo']['savename'];
                $biglogo  = $info['logo']['savepath'].'big_'.$info['logo']['savename'];
                $midlogo  = $info['logo']['savepath'].'mid_'.$info['logo']['savename'];
                $smlogo = $info['logo']['savepath'].'sm_'.$info['logo']['savename'];
                //打开要生成的缩略图的图片
                $image = new \Think\Image();
                $image->open('./Public/Uploads/'.$logo);
                //生成缩略图
                $image->thumb(700,700)->save('./Public/Uploads/'.$mbiglogo);
                $image->thumb(350,350)->save('./Public/Uploads/'.$biglogo);
                $image->thumb(130,130)->save('./Public/Uploads/'.$midlogo);
                $image->thumb(50,50)->save('./Public/Uploads/'.$smlogo);
                //把路径放到表单中
                $data['logo'] = $logo;
                $data['mbig_logo'] = $mbiglogo;
                $data['big_logo'] = $biglogo;
                $data['mid_logo'] = $midlogo;
                $data['sm_logo'] = $smlogo;

                $oldLogo = $this->field('logo,mbig_logo,big_logo,mid_logo,sm_logo')->find($id);//dump($oldLogo);exit;
                deleteImage($oldLogo);
                /*unlink('./Public/Uploads/'.$oldLogo['logo']);
                unlink('./Public/Uploads/'.$oldLogo['mbig_logo']);
                unlink('./Public/Uploads/'.$oldLogo['big_logo']);
                unlink('./Public/Uploads/'.$oldLogo['mid_logo']);
                unlink('./Public/Uploads/'.$oldLogo['sm_logo']);*/

                $data['goods_desc'] = removeXSS($_POST['goods_desc']);
            }
        }
        /***************修改会员价格******************/
        $mp = I('post.member_price');
        $mpMdoel = D('member_price');
        $mpMdoel->where(array('goods_id'=>array('eq',$id),))->delete();
        foreach ($mp as $k => $v){
            $_v = $v;
            if ($_v > 0){
                $mpMdoel->add(array(
                    'price' => $v,
                    'level_id' => $k,
                    'goods_id' => $id
                ));
            }
        }
        /*********** 处理商品相册 ***********/
        if (isset($_FILES['pic'])){
            $pics = array();
            //将$_FILES中的二维数组转为一维数组
            foreach ($_FILES['pic']['name'] as $k => $v) {
                $pics[] = array(
                    'name' => $v,
                    'type' => $_FILES['pic']['type'][$k],
                    'tmp_name' => $_FILES['pic']['tmp_name'][$k],
                    'error' => $_FILES['pic']['error'][$k],
                    'size'  => $_FILES['pic']['size'][$k],
                );
            }
            $_FILES = $pics;
            $gpModel = D('goods_pic');
            foreach ($pics as $k => $v){
                if ($pics['error'] == 0){
                    $ret = uploadOne($k,'Goods',array(
                        array(350,350),
                        array(150,150),
                        array(50,50),
                    ));
                    if ($ret['ok'] == 1){
                        $gpModel ->add(array(
                            'pic' => $ret['images'][0],
                            'big_pic' => $ret['images'][1],
                            'mid_pic' => $ret['images'][2],
                            'sm_pic' => $ret['images'][3],
                            'goods_id' => $data['id'],
                        ));
                    }
                }
            }
        }
    }

    public function _before_delete($option){
        $id = $option['where']['id'];
        $oldLogo = $this->field('logo,mbig_logo,big_logo,mid_logo,sm_logo')->find($id);
        unlink('./Public/Uploads/'.$oldLogo['logo']);
        unlink('./Public/Uploads/'.$oldLogo['mbig_logo']);
        unlink('./Public/Uploads/'.$oldLogo['big_logo']);
        unlink('./Public/Uploads/'.$oldLogo['mid_logo']);
        unlink('./Public/Uploads/'.$oldLogo['sm_logo']);

        $oldLogo = $this->field('logo,mbig_logo,big_logo,mid_logo,sm_logo')->find($id);
        deleteImage($oldLogo);
        $mpModel = D('member_price');
        $mpModel->where(array('goods_id'=>array('eq',$id)))->delete();

        //分类
        $gcModel = D('goods_cat');
        $gcModel->where(array(
            'goods_id' => array('eq',$id),
        ))->delete();

    }

    protected function _after_insert($data,$option){
        /*********商品属性**********/
        $attrValue = I('post.attr_value');
        $gaModel = D('goods_attr');
        foreach ($attrValue as $k => $v){
            $v = array_unique($v);
            foreach ($v as $k1 => $v1){
                if ($v1 != ''){
                    $gaModel->add(array(
                        'goods_id' => $data['id'],
                        'attr_id'  => $k,
                        'attr_value' => $v1,
                    ));
                }

            }
        }
        //商品信息添加后生成拓展分类表数据
        $ecid = I('post.ext_cat_id');
        if ($ecid)
            $gcModel = D('goods_cat');
            foreach ($ecid as $k => $v){
                if (empty($v)){
                    continue;
                }
                $gcModel->add(array(
                    'cat_id'   => $v,
                    'goods_id' => $data['id'],
                ));
            }
        //会员价格
        $mp = I('post.member_price');
        $mpModel = D('member_price');
        foreach ($mp as $k => $v){
            $v = (float)$v;
            if ($v > 0){
                $mpModel->add(array(
                    'price'    => $v,
                    'level_id' => $k,
                    'goods_id' => $data['id']
                ));
            }
        }
    /*************** 处理相册图片 ***************/
        if (isset($_FILES['pic'])){
            $pics = array();
            //将$_FILES中的二维数组转为一维数组
            foreach ($_FILES['pic']['name'] as $k => $v) {
                $pics[] = array(
                  'name' => $v,
                  'type' => $_FILES['pic']['type'][$k],
                  'tmp_name' => $_FILES['pic']['tmp_name'][$k],
                  'error' => $_FILES['pic']['error'][$k],
                  'size'  => $_FILES['pic']['size'][$k],
                );
            }
            $_FILES = $pics;
            $gpModel = D('goods_pic');
            foreach ($pics as $k => $v){
                if ($pics['error'] == 0){
                    $ret = uploadOne($k,'Goods',array(
                        array(350,350),
                        array(150,150),
                        array(50,50),
                    ));
                    if ($ret['ok'] == 1){
                        $gpModel ->add(array(
                            'pic' => $ret['images'][0],
                            'big_pic' => $ret['images'][1],
                            'mid_pic' => $ret['images'][2],
                            'sm_pic' => $ret['images'][3],
                            'goods_id' => $data['id'],
                        ));
                    }
                }
            }
        }
    }

    public function search ($perPage=5){

        $where = array();
        $gn = I('get.gn');
        if ($gn)
            $where['a.shop_price'] = array('like',"%$gn%");
        $fp = I('get.fp');
        $tp = I('get.tp');
        if ($fp && $tp)
            $where['a.shop_price'] = array('between',array($fp,$tp));
        elseif ($fp)
            $where['a.shop_price'] = array('egt',$fp);
        elseif ($tp)
            $where['a.shop_price'] = array('elt',$tp);
        $ios = I('get.ios');
        if($ios !=null && ($ios || $ios ==0))
            $where['a.is_on_sale'] = array('eq',$ios);
        $fa = I('get.fa');
        $ta = I('get.ta');
        if ($fa && $ta)
        {
            $where['addtime'] = array('between',array($fa,$ta));
        }elseif ($fa) {
            $where['addtime'] = array('egt',$fa);
        }elseif ($ta){
            $where['addtime'] = array('elt',$ta);
        }

        //品牌
        $brandId = I('get.brand_id');
        if ($brandId)
            $where['a.brand_id'] = array('eq',$brandId);

        //分类
        $catId = I('get.cat_id');
        if ($catId){
            $gids = $this->getGoodsIdByCatId($catId);
            $children[] = $catId;
            $where['cat_id'] = array('IN',$gids);//a表
        }

        //
        $count = $this->where($where)->count();
        $pageObj = new \Think\Page($count,$perPage);
        $pageObj->setConfig('next','下一页');
        $pageObj->setConfig('prev','上一页');
        $pageString = $pageObj->show();

        $orderby = 'a.id';
        $orderway = 'desc';
        $odby = I('get.odby');
        if ($odby) {
            if ($odby =='id_asc'){
                $orderway = 'asc';
            }elseif($odby == 'price_desc'){
                $orderdy = 'shop_price';
            }elseif ($odby == 'price_asc'){
                $orderby = 'shop_price';
                $orderway = 'asc';
            }
        }

        $data = $this->order("$orderby $orderway")
            ->field('a.*,b.brand_name,c.cat_name,GROUP_CONCAT(e.cat_name SEPARATOR "<br/>") ext_cat_name')
            ->alias('a')
            ->join('LEFT JOIN __BRAND__ b ON a.brand_id=b.id 
                    LEFT JOIN __CATEGORY__ c on a.cat_id=c.id 
                    LEFT JOIN __GOODS_CAT__ d on a.id=d.goods_id 
                    LEFT JOIN __CATEGORY__ e on d.cat_id=e.id')
            ->where($where)
            ->limit($pageObj->firstRow.','.$pageObj->listRows)
            ->group('a.id')
            ->select();
        return array(
            'data' => $data,
            'page' => $pageString,
        );
    }

    //取出一个分类下的所有商品的ID
    public function getGoodsIdByCatId($catId){
        //先取出所有子分类的id
        $catModel = D('Admin/Category');
        $children = $catModel->getChildren($catId);
        $children[] = $catId;
        $gids = $this->field('id')->where(array(
            'cat_id' => array('in',$children),
        ))->select();
        //取出扩展分类下的商品的ID
        $gcModel = D('goods_cat');
        $gids1 = $gcModel->field('DISTINCT goods_id id')->where(array(
            'cat_id' => array('in',$children)
        ))->select();
        if ($gids && $gids1){
            $gids = array_merge($gids,$gids1);
        }elseif ($gids1){
            $gids = $gids1;
        }
        //二维转一维并去重
        $id = array();
        foreach ($gids as $k => $v) {
            if (!in_array($v['id'],$id)){
                $id[] = $v['id'];
            }
        }
        return $id;
    }

    public function getPromoteGoods($limit=5){
        $today = date('Y-m-d H:i');
        return $this->field('id,goods_name,mid_logo,promote_price')
            ->where(array(
                'is_on_sale' => array('eq','是'),
                'promote_price' => array('gt',0),
                'promote_start_date' => array('elt',$today),
                'promote_end_date' => array('egt',$today),
            ))
            ->limit($limit)
            ->order('sort_num ASC')
            ->select();
    }

    public function getRecGoods($recType,$limit=5){
        return $this->field('id,goods_name,mid_logo,shop_price')
            ->where(array(
                'is_on_sale' => array('eq','是'),
                "$recType" => array('eq','是'),
            ))
            ->limit($limit)
            ->select();
    }

    public function getMemberPrice($goodsId) {
        $today = date('Y-m-d H:i');
        $levelId = session('level_id');
        //商品促销信息
        $promotePrice = $this->field('promote_price')->where(array(
            'id' => array('eq',$goodsId),
            'promote_price' => array('gt',0),
            'promote_start_date' => array('elt',$today),
            'promote_end_date' => array('egt',$today),
        ))->find();
        //判断会员有没有登陆
        if ($levelId){
            $mpModel = D('Admin/member_price');
            $mpData = $mpModel->field('price')->where(array(
                'goods_id' => array('eq',$goodsId),
                'level_id' => array('eq',$levelId),
            ))->find();
            //这个级别有没有设置价格
            if ($mpData['price']){
                if ($promotePrice['promote_price'])
                    return min($promotePrice['promote_price'],$mpData['price']);
                else
                    return $mpData['price'];
            } else {
                $p = $this->field('shop_price')->find($goodsId);
                if ($promotePrice['promote_price'])
                    return min($promotePrice['promote_price'],$p['shop_price']);
                else
                    return $p['shop_price'];
            }
        } else {
            $p = $this->field('shop_price')->where(array('id' => 'eq',$goodsId))->find();
            if ($promotePrice['promote_price'])
                return min($promotePrice['promote_price'],$p['shop_price']);
            else
                return $p['shop_price'];
        }
    }

    public function cat_search($catId,$pageSize=60){
        $goodsId = $this->getGoodsIdByCatId($catId);
        $where['a.id'] = array('in',$goodsId);
        //品牌
        $brandId = I('get.brand_id');
        if ($brandId)
            $where['brand_id'] = array('eq',(int)$brandId);
        $price = I('get.price');
        if ($price) {
            $price = explode('-', $price);
            $where['a.shop_price'] = array('between', $price);
        }

        $gaModel = D('goods_attr');
        $attrGoodsId = NULL;
        foreach( $_GET as $k => $v){
            if (strpos($v,'') ===0){
                $attrId = str_replace('attr_','',$k);
                $attrName = strrchr($v,'');
                $attrValue = str_replace($attrName,',',$v);
                $gids = $gaModel->field('GROUP_CONCAT (goods_id) gids')->where(array(
                    'attr_id' => array('eq',$attrId),
                    'attr_value' => array('eq',$attrValue),
                ))->find();
                if ($gids['gids']){
                    $gids['gids'] = explode(',',$gids['gids']);
                    if ($attrGoodsId ===NULL ){
                        $attrGoodsId = $gids['gids'];
                    }else{
                        $attrGoodsId = array_intersect($attrGoodsId,$gids['gids']);
                        if (empty($attrGoodsId)){
                            $where['a.id'] = array('eq',0);
                            break;
                        }
                    }
                }else{
                    $attrGoodsId = array();
                    $where['a.id'] = array('eq',0);
                    break;
                }
            }
        }
        if ($attrGoodsId)
            $where['a.id'] = array('in',$attrGoodsId);

        //翻页
        $count = $this->alias('a')->field('COUNT(a.id) goods_count,GROUP_CONCAT(a.id) goods_id')->where($where)->find();
        $data['goods_id'] = explode(',',$count['goods_id']);

        $page = new \Think\Page($count['goods_count'],$pageSize);
        $page->setConfig('prev' ,'上一页');
        $page->setConfig('next' ,'下一页');
        $data['page'] = $page->show();

        //排序
        $oderby = 'xl';
        $oderway = 'desc';
        $odby = I('get.odby');
        if ($odby){
            if ($odby == 'addtime')
                $oderby = 'a.addtime';
            if (strpos($odby,'price_') === 0){
                $oderby = 'a.shop_price';
                if ($odby == 'price_desc')
                    $oderby = 'asc';
            }
        }


        //数据
        $data['data'] = $this->alias('a')->field('a.id,a.goods_name,a.mid_logo,a.shop_price,SUM(b.goods_number) xl')->join('LEFT JOIN __ORDER_GOODS__ b ON (a.id=b.goods_id) AND b.order_id IN(SELECT id FROM __ORDER__ WHERE pay_status="是")')->where($where)->group('a.id')->limit($page->firstRow.','.$page->listRows)->select();
        return $data;
    }

    /**
     *
     *
     */
    public function key_search($key,$pageSize = 60) {
       $goodsId = $this->alias('a')->field('GROUP_CONCAT(DISTINCT a.id) gids')->join('LEFT JOIN __GOODS_ATTR__ b on a.id=b.goods_id')
           ->where(array(
               'a.is_on_sale' => array('eq','是'),
               'a.goods_name' =>array('exp',"LIKE '%$key%' OR a.goods_desc LIKE '%$key%' OR attr_value LIKE '%$key%'"),
           ))->find();
        $goodsId = explode(',',$goodsId['gids']);

        $where['a.id'] = array('in',$goodsId);
        //品牌
        $brandId = I('get.brand_id');
        if ($brandId)
            $where['a.brand_id'] = array('eq',(int)$brandId);
        //价格
        $price = I('get.price');
        if ($price){
            $price = explode('-',$price);
            $where['a.shop_price'] = array('between' ,$price);
        }

    }

}